import React, {
    Component,
} from 'react';
import LinearGradient from 'react-native-linear-gradient';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    StatusBar,
    NativeModules,
    ScrollView,
    Switch, DeviceEventEmitter, ActivityIndicator,
    ToastAndroid,
    Clipboard,
    Alert,
    ImageBackground
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import { ToastToUser } from "../../utils/CustomToast";
import AndroidModule from "../../utils/AndroidConnent";
import Header from '../../components/header';
import { TextInput } from 'react-native';
import Constant from '../../utils/Constant'
import Loading from "../../utils/Loading";
import CommonAlertView from "../common/CommonAlertView";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const bannerHeight = screenW * 0.61;
const vinCodeLength = 17
let navigation

export default class FoursQuery extends Component {

    constructor(props) {
        super(props);
        let vcode = this.props.route && this.props.route.params && this.props.route.params.vcode ? this.props.route.params.vcode : ''
        this.state = {
            selecTypeIndex: 0,
            vinCode: vcode, //手输vin码
            matchResult: [], //匹配的维保记录
            manualMatchResult: [], //手输vin之后匹配的维保记录
            inStoreMatchResult: [], //选择在库车辆之后匹配的维保记录
            availAmount: 0,
            showMoreBtn: false,
            carInfo: {},
            showMenu: false,
            showAlertView: false,
        }
    }

    componentWillUnmount() {
        if (this.selectCarEvent) {
            this.selectCarEvent.remove();
        }
        if (this.paySuccess) {
            this.paySuccess.remove();
        }
    }

    componentWillMount() {
        this.selectCarEvent = DeviceEventEmitter.addListener('commonEvent', e => {
            if (e.type == 'selectCar') {
                this.setState({
                    carInfo: isIos ? e.car : JSON.parse(e.car)
                }, function () {
                    this.requestMatchedRecords()
                })
            } else if (e.type == 'vinScan') {
                this.setState({
                    vinCode: e.vcode
                }, function () {
                    this.requestMatchedRecords()
                })
            }
        });

        this.paySuccess = DeviceEventEmitter.addListener('paySuccess', e => {
            this.requestavailAmount()
        });

        if (this.state.vinCode && this.state.vinCode.length == 17) {
            this.submitFoursOrder()
        }

    }

    componentDidMount() {
        if (this.props.vin && this.props.vin != '') {
            this.setState({
                vinCode: this.props.vin
            })
        }
        this.requestavailAmount()
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'维保查询'} RightButton={() => this.renderRightButton()}></Header>
                <ScrollView showsVerticalScrollIndicator={false} style={{ flex: 1, backgroundColor: '#FFDB1B' }}>
                    <View style={styles.topView} />
                    <Image source={require('source/image/weibao/weibao_banner.png')} style={styles.bannerIcon} />
                    <View style={styles.contentContainer}>
                        <View style={styles.contentBg}>
                            {this.renderTypeBox()}
                            <View style={{ paddingTop: 21, paddingBottom: 20, paddingHorizontal: 10, }}>
                                {this.renderVinInput()}
                                {
                                    JSON.stringify(this.state.carInfo) != '{}' && this.state.selecTypeIndex == 1 ?
                                        <TouchableOpacity
                                            style={styles.carInfoBox}
                                        >
                                            <Image defaultSource={require('source/image/comm/sc_default.png')} style={{ width: 36, height: 36, borderRadius: 18 }} source={{ uri: Constant.imgDomain + this.state.carInfo.mainPic + '?x-oss-process=style/carpic_list' }} />
                                            <Text style={styles.carInfoBrand}>{this.state.carInfo.seriesName + ' ' + this.state.carInfo.speciesName}</Text>
                                        </TouchableOpacity>
                                        :
                                        null
                                }
                                {
                                    (this.state.selecTypeIndex == 0 && this.state.vinCode.length < vinCodeLength) || (this.state.selecTypeIndex == 1 && !this.state.carInfo.vcode) ?
                                        null
                                        :
                                        this.state.matchResult.length == 0 ?
                                            <Text style={styles.noMatchText}>帅车联盟暂未匹配到维保记录</Text>
                                            :
                                            this.renderMatchListView()
                                }

                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    style={styles.searchBox}
                                    onPress={() => {
                                        this.submitFoursOrder()
                                    }}
                                >
                                    <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }}
                                        colors={['#FFAE5A', '#FA6A06']}
                                        style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center', borderRadius: 4 }}
                                    >
                                        <Text style={styles.searchText}>查询</Text>
                                    </LinearGradient>
                                </TouchableOpacity>

                                <View style={styles.cashBox}>
                                    <Text style={styles.cashText}>{'余额：' + (this.state.availAmount / 100).toFixed(2) + '元'}</Text>
                                    <TouchableOpacity
                                        onPress={() => {
                                            this.pushToRecharge()
                                            // this.setState({
                                            //     showAlertView: true
                                            // })
                                        }}
                                    >
                                        <Text style={styles.rechargeText}>{'充值>>'}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        <View style={{ height: 40 }} />
                    </View>
                </ScrollView>
                {
                    this.state.showMenu ?
                        <TouchableOpacity
                            style={styles.moreItemsBg}
                            onPress={() => {
                                this.setState({
                                    showMenu: false
                                })
                            }}
                            activeOpacity={1.0}
                        >
                            <ImageBackground style={[styles.moreItemsBox, { top: isIos ? Constant.statusBarHeight + 20 : 20 }]} source={require('source/image/weibao/more_items.png')}>
                                <TouchableOpacity
                                    style={styles.itemBox}
                                    onPress={() => {
                                        this.setState({
                                            showMenu: false
                                        })
                                        navigation.navigate('FoursQueryHistory')
                                    }}
                                >
                                    <Text style={styles.itemText}>我的维保记录</Text>
                                </TouchableOpacity>
                                <View style={styles.sepLine} />
                                <TouchableOpacity
                                    style={styles.itemBox}
                                    onPress={() => {
                                        this.setState({
                                            showMenu: false
                                        })
                                        navigation.navigate('FoursQueryCostRecord')
                                    }}
                                >
                                    <Text style={styles.itemText}>历史账单</Text>
                                </TouchableOpacity>
                            </ImageBackground>
                        </TouchableOpacity>
                        :
                        null
                }

                {
                    this.state.showAlertView ?
                        <CommonAlertView
                            title={'暂不支持自动充值，请联系客服进行充值'}
                            sureDes={'好的'}
                            sureAction={() => {
                                this.setState({
                                    showAlertView: false,
                                }, function () {
                                    navigation.navigate('ContactUs')
                                })
                            }}
                        />
                        : null
                }


                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderRightButton() {
        return (
            <TouchableOpacity
                style={styles.moreContainer}
                activeOpacity={0.8}
                onPress={() => {
                    this.moreAction()
                }}>
                <Image style={styles.moreIcon} source={require('source/image/more_icon.png')} />
            </TouchableOpacity>
        )
    }

    renderTypeBox() {
        return (
            <View style={styles.typeBg}>
                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.typeBox}
                    onPress={() => {
                        let manualMatchResult = this.state.manualMatchResult
                        this.setState({
                            selecTypeIndex: 0,
                            matchResult: manualMatchResult
                        })
                    }}
                >
                    {
                        this.state.selecTypeIndex == 0 ?
                            <Text style={styles.selSearchTypeText}>VIN码查询</Text>
                            :
                            <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }}
                                colors={['#FA6A06', '#FFAD5A']}
                                style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center', borderTopLeftRadius: 4 }}
                            >
                                <Text style={styles.searchTypeText}>VIN码查询</Text>
                            </LinearGradient>
                    }

                </TouchableOpacity>
                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.typeBox}
                    onPress={() => {
                        let inStoreMatchResult = this.state.inStoreMatchResult
                        this.setState({
                            selecTypeIndex: 1,
                            matchResult: inStoreMatchResult
                        })
                    }}
                >
                    {
                        this.state.selecTypeIndex == 1 ?
                            <Text style={styles.selSearchTypeText}>在库车辆查询</Text>
                            :
                            <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }}
                                colors={['#FA6A06', '#FFAD5A']}
                                style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center', borderTopRightRadius: 4 }}
                            >
                                <Text style={styles.searchTypeText}>在库车辆查询</Text>
                            </LinearGradient>
                    }

                </TouchableOpacity>
            </View>
        )
    }

    renderVinInput() {
        if (this.state.selecTypeIndex == 0) {
            return (
                <View style={styles.inputBox}>
                    <TextInput
                        keyboardType={isIos ? 'ascii-capable' : 'default'}
                        autoCorrect={false}
                        editable={true}
                        returnKeyType='done'
                        autoCapitalize='characters'
                        style={styles.textInput}
                        placeholder={'请输入' + vinCodeLength + '位VIN码'}
                        placeholderTextColor="#999999"
                        value={this.state.vinCode}
                        onChangeText={this.onCodeChangeText}
                    />
                    <View style={styles.rightInputBox}>
                        <Text style={styles.vinLengthText}>{this.state.vinCode.length + '/' + vinCodeLength}</Text>
                        <TouchableOpacity
                            style={styles.scanBox}
                            onPress={() => {
                                AndroidModule.selectCarVin({}, (error, result) => {
                                    this.setState({
                                        vinCode: result
                                    }, function () {
                                        this.requestMatchedRecords()
                                    })
                                })
                            }}
                        >
                            <Image style={styles.scanIcon} source={require('source/image/weibao/vin_scan.png')} />
                        </TouchableOpacity>
                    </View>
                </View>
            )
        } else {
            return (
                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.inputBox}
                    onPress={() => {
                        this.selectCar()
                    }}
                >
                    <Text style={[styles.brandText, { color: this.state.carInfo.vcode && this.state.carInfo.vcode.length == vinCodeLength ? '#333333' : '#999999' }]}>
                        {this.state.carInfo.vcode && this.state.carInfo.vcode.length == vinCodeLength ? this.state.carInfo.vcode : '请选择在库车辆'}
                    </Text>
                    <Image style={styles.arrowIcon} source={require('source/image/comm/icon_tree_arrow.png')} />
                </TouchableOpacity>
            )
        }
    }

    renderMatchListView() {
        return (
            <View style={{ flexDirection: 'column', alignItems: 'center' }}>
                <Text style={[styles.noMatchText, { marginTop: 18 }]}>{'帅车联盟已为您匹配了' + this.state.matchResult.length + '条维保记录'}</Text>
                <View style={styles.matchBg}>
                    {
                        this.state.matchResult.map((item, index) => {
                            if (this.state.showMoreBtn && index > 1) {
                                return (
                                    null
                                )
                            }
                            return (
                                <View style={[styles.matchItemBox, { borderBottomWidth: (index == this.state.matchResult.length - 1) || (this.state.showMore && index == 1) ? 0 : 0.5 }]}>
                                    <Image defaultSource={{ uri: 'sc_default' }} style={styles.headImg} source={{ uri: Constant.imgDomain + item.merchantLogoPic }} />
                                    <View style={styles.matchItemDesBox}>
                                        <Text style={styles.matchItemDesText}>{(item.merchantName ? item.merchantName : '') + '分享了维保记录'}</Text>
                                        <Text style={styles.matchItemTimeText}>{item.createTime}</Text>
                                    </View>
                                    <TouchableOpacity
                                        style={styles.lookBox}
                                        activeOpacity={0.8}
                                        onPress={() => {
                                            // let obj = {
                                            //     url: Constant.webDomain + '/insurance?fid=' + item.id,
                                            //     param: {
                                            //         carName: item.carName ? item.carName : '--',
                                            //         brandLogo: item.brandLogo ? item.brandLogo : '--',
                                            //         vcode: item.vcode ? item.vcode : '--',
                                            //         reportType: item.reportType + ''
                                            //     }
                                            // }
                                            // AndroidModule.jumptypeCommon(obj);
                                            let url = Constant.webDomain + '/insurance?fid=' + item.id
                                            navigation.navigate('WebView', { source: url })
                                        }}
                                    >
                                        <Text style={styles.lookText}>查看</Text>
                                    </TouchableOpacity>
                                </View>
                            )
                        })
                    }
                    {
                        this.state.showMoreBtn ?
                            <TouchableOpacity
                                style={styles.moreBox}
                                onPress={() => {
                                    this.setState({
                                        showMoreBtn: false
                                    })
                                }}
                            >
                                <Text style={{ color: '#F99802', fontSize: 12 }}>查看更多</Text>
                            </TouchableOpacity>
                            :
                            null
                    }
                </View>
            </View>
        )
    }

    onCodeChangeText = (value) => {
        let subValue = value
        if (value.length > vinCodeLength) {
            subValue = value.substring(0, vinCodeLength)
        }
        if (this.state.vinCode != subValue) {
            this.setState({
                vinCode: subValue
            }, function () {
                if (this.state.vinCode.length == vinCodeLength) {
                    this.requestMatchedRecords()
                } else {
                    this.setState({
                        manualMatchResult: [],
                        matchResult: []
                    })
                }
            })
        }
    }

    requestMatchedRecords() {
        let vcode = ''
        if (this.state.selecTypeIndex == 0) {
            vcode = this.state.vinCode
        } else {
            vcode = this.state.carInfo.vcode
        }
        let param = {
            vcode: vcode,
            pageNo: 1,
            pageSize: 20,
            queryStatus: 1, //查询成功的记录
            reportType: '1', //维保
        }
        HttpUtils.postRequest(HttpUrls.maintenanceRecords, param)
            .then((result) => {
                let success = result.success
                if (success == true) {
                    let tempResultList = result.data.resultList
                    let resultList = []
                    tempResultList.map((item) => {
                        let merchantName = item.merchantName
                        if (merchantName && merchantName.indexOf('(') != -1) {
                            merchantName = merchantName.substring(0, merchantName.indexOf('('))
                        }
                        item.merchantName = merchantName
                        resultList.push(item)
                    })
                    if (this.state.selecTypeIndex == 0) {
                        this.setState({
                            manualMatchResult: resultList
                        })
                    } else {
                        this.setState({
                            inStoreMatchResult: resultList
                        })
                    }
                    this.setState({
                        matchResult: resultList,
                        showMoreBtn: resultList.length > 2 ? true : false
                    })
                }
            })
            .catch((error) => {

            });
    }

    requestavailAmount() {
        HttpUtils.getRequest(HttpUrls.merchantAccountDetail, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    this.setState({
                        availAmount: data.availAmount ? parseFloat(data.availAmount) : 0,
                    })
                }
            })
            .catch((error) => {

            });
    }

    moreAction() {
        this.setState({
            showMenu: true
        })
    }

    pushToRecharge() {
        navigation.navigate('FundAccountPage')
    }

    selectCar() {
        navigation.navigate('FoursCarSelectPage', {
            completion: (carInfo) => {
                navigation.goBack()
                this.setState({
                    carInfo: carInfo
                }, function () {
                    this.requestMatchedRecords()
                })
            }
        })
    }

    submitFoursOrder() {
        if (this.state.selecTypeIndex == 0) {
            if (this.state.vinCode.length < vinCodeLength) {
                console.log('vinCodeLength = ', vinCodeLength)
                ToastToUser('请输入' + vinCodeLength + '位VIN码')
                return
            }
        } else if (this.state.selecTypeIndex == 1) {
            if (!this.state.carInfo || !this.state.carInfo.vcode) {
                ToastToUser('请选择在库车辆查询')
                return
            }
        }

        let vcode = ''
        if (this.state.selecTypeIndex == 0) {
            vcode = this.state.vinCode
        } else {
            vcode = this.state.carInfo.vcode
        }
        let param = {
            vin: vcode,
        }

        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.getCarMaintenanceOrder, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let success = result.success
                if (success == true) {
                    navigation.navigate('FoursQuerySubmit', { data: JSON.stringify(result.data) })
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    moreContainer: {
        position: 'absolute',
        right: 0,
        width: 60,
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center'
    },
    moreIcon: {
        width: 20,
        height: 20,
    },
    bannerIcon: {
        width: '100%',
        height: bannerHeight
    },
    topView: {
        width: '100%',
        height: 2000,
        marginTop: -2000,
        backgroundColor: '#f6f6f6'
    },
    contentContainer: {
        flex: 1,
        paddingTop: 0,
        paddingHorizontal: 10
    },
    contentBg: {
        backgroundColor: '#FEF3D4',
        borderRadius: 5,
        width: '100%',
        flexDirection: 'column'
    },
    typeBg: {
        flexDirection: 'row',
        height: 45,
        width: '100%',
    },
    typeBox: {
        width: '50%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center'
    },
    typeSelectBox: {
        width: '50%',
        height: '100%',
    },
    selSearchTypeText: {
        color: '#FF6100',
        fontSize: 15,
        fontWeight: '500'
    },
    searchTypeText: {
        color: '#FFFFFF',
        fontSize: 15,
    },
    inputBox: {
        width: '100%',
        height: 44,
        backgroundColor: '#fff',
        borderRadius: 5,
        flexDirection: 'row',
        alignItems: 'center'
    },
    textInput: {
        paddingLeft: 10,
        color: '#333333',
        fontSize: 14,
        width: screenW - 120,
        height: '100%',
    },
    brandText: {
        paddingLeft: 10,
        color: '#333333',
        fontSize: 14,
        width: screenW - 120,
    },
    rightInputBox: {
        flexDirection: 'row',
        alignItems: 'center',
        position: 'absolute',
        right: 0,
    },
    vinLengthText: {
        color: '#222222',
        fontSize: 12,
    },
    scanBox: {
        width: 42,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center'
    },
    scanIcon: {
        width: 18,
        height: 18
    },
    arrowIcon: {
        position: 'absolute',
        right: 10,
        width: 15,
        height: 15
    },
    carInfoBox: {
        width: '100%',
        height: 66,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5
    },
    carInfoBrand: {
        flex: 1,
        marginLeft: 10,
        color: '#222222',
        fontSize: 15,
        fontWeight: '500'
    },
    noMatchText: {
        marginTop: 28,
        color: '#999999',
        fontSize: 12,
        textAlign: 'center'
    },
    searchBox: {
        marginTop: 28,
        width: '100%',
        height: 50,
    },
    searchText: {
        color: '#FFFFFF',
        fontSize: 15
    },
    cashBox: {
        marginTop: 18,
        height: 30,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    cashText: {
        fontSize: 14,
        color: '#222222'
    },
    rechargeText: {
        color: '#FB3D3C',
        fontSize: 14
    },
    matchBg: {
        paddingHorizontal: 10,
        marginTop: 18,
        backgroundColor: '#fff',
        borderRadius: 4,
        width: '100%'
    },
    matchItemBox: {
        width: '100%',
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#E4E4E4'
    },
    headImg: {
        width: 36,
        height: 36,
        borderRadius: 18,
    },
    matchItemDesBox: {
        flexDirection: 'column',
        marginLeft: 13,
        flex: 1,
    },
    matchItemDesText: {
        maxHeight: 34,
        lineHeight: 17,
        marginRight: 90,
        color: '#222222',
        fontSize: 12,
        fontWeight: '500'
    },
    matchItemTimeText: {
        marginTop: 3,
        color: '#999999',
        fontSize: 11,
    },
    lookBox: {
        position: 'absolute',
        right: 4,
        width: 72,
        height: 26,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#F99802',
        justifyContent: 'center',
        alignItems: 'center'
    },
    lookText: {
        color: '#F99802',
        fontSize: 14
    },
    moreBox: {
        width: '100%',
        height: 40,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    moreItemsBg: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        // backgroundColor: 'rgba(0,0,0,0.3)'
    },
    moreItemsBox: {
        position: 'absolute',
        right: 8,
        top: 44,
        width: 150,
        height: 175,
        paddingTop: 44,
        flexDirection: 'column',
        alignItems: 'flex-end',
    },
    itemBox: {
        width: '100%',
        height: 44,
        width: 108,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    itemText: {
        marginRight: 10,
        color: '#000000',
        fontSize: 15
    },
    sepLine: {
        backgroundColor: '#E7E7E7',
        height: 0.5,
        width: 98,
        marginRight: 10,
    },

})